<template>
  <cl-form ref="Form" />
</template>

<script lang="ts" name="dept-move" setup>
import { useCool } from "/@/cool";
import { ElMessage, ElMessageBox } from "element-plus";
import { useCrud, useForm } from "@cool-vue/crud";
import dayjs from "dayjs";

const { service } = useCool();

// cl-form
const Form = useForm();

// cl-crud
const Crud = useCrud();

// 打开
async function open(dept: any) {
	Form.value?.open({
		title: "导出",
		width: "400px",
		op: {
			saveButtonText: "导出"
		},
		props: {
			labelWidth: "110px",
			labelPosition: "top"
		},
		items: [
			{
				prop: "type",
				value: "1",
				component: {
					name: "el-radio-group",
					options: [
						{
							label: "全部",
							value: "1"
						},
						{
							label: "增员",
							value: "2"
						},
						{
							label: "减员",
							value: "3"
						}
					]
				}
			},
			{
				prop: "datespan",
				value: [dayjs(), dayjs()],
				hidden: ({ scope }) => {
					return scope.type == "1";
				},
				component: {
					name: "el-date-picker",
					props: {
						type: "daterange",
						style: "width:340px",
						startPlaceholder: "开始日期",
						endPlaceholder: "结束日期"
					}
				}
			}
		],
		on: {
			submit(data, { done, close }) {
				// if (!data.datespan) {
				// 	ElMessage.warning("请选择日期");
				// 	return done();
				// }
				service
					.request({
						method: "post",
						url: "/admin/demo/goods/export",
						data: {
							type: data.type,
							datespan: data.datespan
								? [
										dayjs(
											dayjs(data.datespan[0]).format("YYYY-MM-DD") +
												"T00:00:00.000Z"
										),
										dayjs(
											dayjs(data.datespan[1]).format("YYYY-MM-DD") +
												"T23:59:59.999Z"
										)
								  ]
								: [],
							departmentId: dept.id
						},
						responseType: "blob"
					})
					.then((res) => {
						const blob = new Blob([res], { type: res.type });
						const url = window.URL.createObjectURL(blob);
						const link = document.createElement("a");
						link.style.display = "none";
						link.href = url;
						link.download = dept.name + ".xlsx";
						document.body.appendChild(link);
						link.click();
						document.body.removeChild(link); // 下载完成移除元素
						window.URL.revokeObjectURL(url); // 释放掉blob对象
						done();
					})
					.catch((err) => {
						ElMessage.error(err.message);
						done();
					});
			}
		}
	});
}

defineExpose({
	open
});
</script>
